<?php

namespace serv\task\warehouse;

use of;
use of\base\com\mq;
use L;
use Eccang\OpenApi\Contracts\Config;
use Eccang\OpenApi\Eccang as callApi;
use Eccang\OpenApi\System\Request\AppUnityRequest;
use traits\SystemTrait;


class eccang
{
    //同步易仓所有仓库列表
    public static function warehouseList()
    {
        set_time_limit(0);
        try {
            $page_size = 100;
            $current_page = 1;
            do {
                $data = [
                    'page' => $current_page,
                    'page_size' => $page_size
                ];
                $response = self::callApi('getWarehouseList', $data);
                if (!empty($response['data']->getData())) {
                    //表接口获取回来的仓库列表同步的数据库
                    foreach ($response['data']->getData() as $k => $v) {
                        $key = 'eccangWarehouseList_' . $current_page . '_' . $k;
                        //echo json_encode($v, JSON_UNESCAPED_UNICODE); exit;
                        mq::set(["eccangWarehouseList", $key], $v);
                    }
                    $total_page = ceil($response['data']->getTotal() / $page_size);
                } else {
                    $total_page = 1;
                }
                $current_page++;
            } while ($current_page <= $total_page);

            return true;
        } catch (Exception $exp) {
            return false;
        }
    }

    //同步仓库详情
    public static function warehouseDetail()
    {
        $sql = "SELECT id, warehouse_id, warehouse_code FROM warehouse WHERE 1 AND type = 20 AND sync = 0 AND status = 1 LIMIT 10;";
        $result = L::sql($sql, 'warehouse');
        if (!empty($result)) {
            //同步仓库详情
            $rows = array_chunk(array_column($result, 'warehouse_code'), 20);
            foreach ($rows as $k => $v) {
                $key = 'eccangWarehouseDetail_' . $k;
                $data = [
                    'warehouse_code_list' => $v
                ];
                mq::set(["eccangWarehouseDetail", $key], $data);
            }
            //同步区域列表及库位列表
            foreach ($result as $wk => $wv) {
                $data = [
                    'warehouse_id' => $wv['warehouse_id']
                ];
                $key = 'eccangAreaList_' . $wv['id'];
                mq::set(["eccangAreaList", $key], $data);

                $key = 'eccangPositionList_' . $wv['id'];
                mq::set(["eccangPositionList", $key], $data);
            }
        }
    }

    //同步易仓的海外仓库库存
    public static function pull()
    {
        $sql = "SELECT id, warehouse_id, warehouse_code FROM warehouse WHERE 1 AND type = 20 AND status = 1;";
        $result = L::sql($sql, 'warehouse');
        if (!empty($result)) {
            foreach ($result as $k => $v) {
                $key = 'eccangPullStock_' . $v['id'];
                //echo json_encode($v); exit;
                mq::set(["eccangPullStock", $key, $k * 10], $v);
            }
        }
    }

    //同步产品信息
    public static function productList()
    {
        set_time_limit(0);
        try {
            $page_size = 500;
            $current_page = 10;
            do {
                $data = [
                    'page' => $current_page,
                    'page_size' => $page_size
                ];
                $response = self::callApi('getWmsProductList', $data);
                if (!empty($response['data']->getData())) {
                    //表接口获取回来的仓库列表同步的数据库
                    foreach ($response['data']->getData() as $k => $v) {
                        //同步完成之后要把此段删除
                        $key = "checkProduct" . $current_page . $v['product_sku'];
                        //echo json_encode($v, JSON_UNESCAPED_UNICODE); exit;
                        mq::set(["checkProduct", $key, $current_page * ($k + 1) * 2], $v);
                    }
                    $total_page = ceil($response['data']->getTotal() / $page_size);
                } else {
                    $total_page = 1;
                }
                $current_page++;
            } while ($current_page <= $total_page);

            return true;
        } catch (Exception $exp) {
            return false;
        }
    }

    //同步易仓分类
    public static function categoryList()
    {
        set_time_limit(0);
        try {
            $page_size = 500;
            $current_page = 1;
            do {
                $data = [
                    'page' => $current_page,
                    'page_size' => $page_size
                ];
                $response = self::callApi('categotyList', $data);
                if (!empty($response['data']->getData())) {
                    //更新分类
                    $rows = $response['data']->getData();
                    foreach ($rows as $k => $v) {
                        //同步完成之后要把此段删除
                        $key = "checkCategoryList" . $current_page . $v['pc_id'];
                        mq::set(["checkCategoryList", $key, $current_page * ($k + 1) * 2], $v);
                    }
                    $total_page = ceil($response['data']->getTotal() / $page_size);
                } else {
                    $total_page = 1;
                }
                $current_page++;
            } while ($current_page <= $total_page);

            return true;
        } catch (Exception $exp) {
            return false;
        }
    }

    //同步易仓的订单数据
    public static function getOrderList()
    {
        set_time_limit(0);
        try {
            $page_size = 100;
            $current_page = 1;
            $date = date('Y-m-d', strtotime("-1 day"));
            do {
                $data = [
                    'page' => $current_page,
                    'page_size' => $page_size,
                    'get_detail' => 1,
                    'get_address' => 1,
                    'get_custom_order_type' => 1,
                    'condition' => [
                        'warehouse_ship_date_start' => "{$date} 00:00:00",
                        'warehouse_ship_date_end' => "{$date} 23:59:59"
                    ]
                ];
                $response = self::callApi('getOrderList', $data);
                if (!empty($response['data']->getData())) {
                    //更新分类
                    $rows = $response['data']->getData();
                    foreach ($rows as $k => $v) {
                        //同步完成之后要把此段删除
                        //echo json_encode($v, JSON_UNESCAPED_UNICODE); exit;
                        $key = "checkEccangOrder_" . $current_page . $v['refrence_no_sys'];
                        mq::set(["checkEccangOrder", $key, $current_page * ($k + 1) * 1], $v);
                    }
                    $total_page = ceil($response['data']->getTotal() / $page_size);
                } else {
                    $total_page = 1;
                }
                $current_page++;
            } while ($current_page <= $total_page);

        } catch (Exception $exp) {
            echo $exp->getMessage();
        }
    }

    //计算当天各平台的销量
    public static function calcStock()
    {
        $teams = SystemTrait::confing('teamForStock');
        $sql = "SELECT warehouse_sku, SUM(warehouse_sku_qty) AS total, team_name, warehouse_id FROM `order_warehouse_detail` AS a 
                LEFT JOIN order_warehouse AS b ON a.order_id = b.id
                WHERE 1 
                AND b.`status`= 0 
                GROUP BY warehouse_sku, team_name, warehouse_id";
        $result = L::sql($sql, 'warehouse');
        if (!empty($result)) {
            foreach ($result as $v) {
                $belong = isset($teams[$v['team_name']]) ? $teams[$v['team_name']] : of::config('env.PUBLIC_BELONG');
                $sql = "UPDATE stock SET stock = IF(stock - {$v['total']} > 0, stock - {$v['total']} , 0), available_stock = IF(available_stock - {$v['total']} > 0,  available_stock - {$v['total']}, 0) WHERE 1
                        AND warehouse_id = '{$v['warehouse_id']}' 
                        AND sku_code = '{$v['warehouse_sku']}'
                        AND belong = '{$belong}'";
                L::sql($sql, 'warehouse');
            }
        }
    }
    
    //同步易仓库的订单数据
    public static function getOrderListLite()
    {
        set_time_limit(0);
        try {
            $data = [
                'page' => 1,
                'page_size' => 50,
                'year' => 2024
            ];
            $response = self::callApi('getOrderListLite', $data);
            echo '<pre />';
            print_r($response);
            return true;
        } catch (Exception $exp) {
            return false;
        }
    }



    //获取用户列表
    public static function getUser()
    {
        set_time_limit(0);
        try {
            $data = [
                'user_status' => 1,
            ];
            $response = self::callApi('getUser', $data);
            $rows = $response['data']->getData();
            if (!empty($rows)) {
                foreach ($rows as $v) {
                    $password_salt = self::salt();
                    $password = md5('123456' . $password_salt);
                    //$sql = "UPDATE member SET password = '{$password}', password_salt = '{$password_salt}' WHERE 1 AND name = '{$v['user_name']}';";
                    $sql = "INSERT INTO member(`name`, password, password_salt, nickname) VALUES ('{$v['user_name']}', '{$password}', '{$password_salt}', '{$v['user_name_en']}');";
                    echo $sql;
                    echo '<br />';
                }
            }
            return true;
        } catch (Exception $exp) {
            return false;
        }
    }


    //获取仓发信息
    public static function getOrderInfo($warehouse_order_code)
    {
        set_time_limit(0);
        try {
            $data = [
                'warehouse_order_code' => $warehouse_order_code
            ];
            $response = self::callApi('getOrderInfo', $data);
            echo '<pre />';
            print_r($response);
            return true;
        } catch (Exception $exp) {
            return false;
        }
    }



    public static function getTransferBatchList()
    {
        set_time_limit(0);
        try {
            $data = [
                'page' => 1,
                'page_size' => 1
            ];
            $response = self::callApi('getStpoListNew', $data);
            echo '<pre />';
            print_r($response);
            return true;
        } catch (Exception $exp) {
            return false;
        }
    }

    /*
     * 因为易仓的SDK 接口基本都是传调用的方法及请求参数，故封闭成一个方法供其它类调用即可
     *
     */
    private static function callApi($method, $bizContent)
    {
        try {
            $config = new Config();
            $config->setAppKey(of::config('env.ECCANG.appKey'))
                ->setServiceId(of::config('env.ECCANG.serviceId'))
                ->setAppScrete(of::config('env.ECCANG.secret'))
                ->setNonceStr(time());
            $request = new AppUnityRequest();
            $request->setInterfaceMethod($method)
                ->setBizContent($bizContent);
            return [
                'code' => 200,
                'data' => callApi::system($config)->appUnity($request),
                'message' => ''
            ];
        } catch (\Exception $exception) {
            return [
                'code' => 500,
                'data' => [],
                'message' => $exception->getMessage()
            ];
        }
    }

    private static function salt()
    {
        $number = range(0, 9);
        $lowerLetter = range('a', 'z');
        $upperLetter = range('A', 'Z');
        $charset = array_merge($number, $lowerLetter, $upperLetter);
        shuffle($charset);
        for ($i = 10; $i < 20; $i++) {
            $saltArr[] = $charset[$i];
        }
        return implode("", $saltArr);
    }

}